/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bsc.mina.service;

import com.bsc.minacommand.common.CommandState;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.statemachine.StateMachine;
import org.apache.mina.statemachine.StateMachineFactory;
import org.apache.mina.statemachine.StateMachineProxyBuilder;
import org.apache.mina.statemachine.annotation.IoHandlerTransition;
import org.apache.mina.statemachine.context.IoSessionStateContextLookup;
import org.apache.mina.statemachine.context.StateContext;
import org.apache.mina.statemachine.context.StateContextFactory;

/**
 *
 * @author penn
 */
public class MinaStateMachine {

    public static IoHandler createIoHandler(CommandState commandState, Object[] obj) {
        /*
         * 使用ServerHandler创建状态机。
         * 通知状态机工厂使用@IoHandlerTransition标签创建状态机。
         * 使用IoHandlerTransition标签创建ServerHandler实例，
         * 该实例中所有方法进加入IoHandlerTaransition标签，
         * 当输入流(command)中含有对应方名的指令，则方法被调用
         */
        StateMachine sm = StateMachineFactory.getInstance(
                IoHandlerTransition.class).create(commandState.CONNECTED, commandState, obj);
        /**
         * 创建IoHandler实例 设置IoSession状态查找 状态内容工厂创建TetrisServerContext状态实例，并将该实例加入到IoSession状态中。
         *
         */
        return new StateMachineProxyBuilder().setStateContextLookup(
                new IoSessionStateContextLookup(new StateContextFactory() {
            public StateContext create() {
                return new DefaultHandler.ServerContext();
            }
        })).create(IoHandler.class, sm);
    }
}
